import Taro, { Component } from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtTimeline } from "taro-ui";
import { connect } from "@tarojs/redux";
import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import customParseFormat from "dayjs/plugin/customParseFormat";

import { onCheckTodayPlan, onSetCurrentMission } from "../../actions/checkPlan";
import "./timeLine.less";

dayjs.extend(isSameOrAfter);
dayjs.extend(customParseFormat);

const OUT_OF_RANGE = "OUT_OF_RANGE",
  BETW_THE_MISSION = "BETW_ONE_MISSION",
  IN_ONE_MISSION = "IN_ONE_MISSION",
  BEFORE_START = "BEFORE_START",
  AFTER_END = "AFTER_END";

@connect(
  state => state,
  { onCheckTodayPlan, onSetCurrentMission }
)
class TimeLine extends Component {
  checkTodayPlan = () => {
    let today = new Date(),
      data = {
        user: this.props.user.openid,
        days: [
          dayjs(
            `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`
          ).format("YYYY-MM-DD")
        ]
      };
      
    this.props.onCheckTodayPlan(data);
  };

  componentDidMount() {
      this.checkTodayPlan()
  }

  findExecuteMissionNow(items, executeDay) {
    const now = dayjs();
    let index = -1;
    let state = OUT_OF_RANGE;
    let dayjsItems=items.map((v)=>{
      return {
        ...v,
        startTime:dayjs(executeDay + " " + v.startTime),
        endTime:dayjs(executeDay + " " + v.endTime)
      }
    })
    dayjsItems.forEach((el, i) => {
      const startTime = el.startTime,
        endTime = el.endTime;
      startTime.add(1, "year");
      endTime.add(1, "year");
      now.isSameOrAfter(startTime) && now.isBefore(endTime)
        ? ((index = i), (state = IN_ONE_MISSION))
        : null;
    });
    state === IN_ONE_MISSION
      ? null
      : now.isBefore(dayjsItems[0].startTime)
      ? (state = BEFORE_START)
      : now.isSameOrAfter(dayjsItems[dayjsItems.length-1].endTime)
      ? (state = AFTER_END)
      : ((index = dayjsItems.indexOf(
        dayjsItems.reduce((prev, curr) => {
            return now.isSameOrAfter(prev.endTime) &&
              now.isBefore(curr.startTime)
              ? prev
              : curr;
          })
        )),
        (state = BETW_THE_MISSION));
    return { index, state };
  }

  getTimeLineItems = allItems => {
    let finishedItems = [],
      unfinishedItems = [];
    let { index, state } = this.findExecuteMissionNow(
      allItems[0].missions,
      allItems[0].executeDay
    );
    switch (state) {
      case IN_ONE_MISSION:
        finishedItems = allItems[0].missions.slice(0, index + 1);
        unfinishedItems = allItems[0].missions.slice(
          index + 1,
          allItems[0].missions.length
        );
        this.props.onSetCurrentMission(allItems[0].missions[index].missionName);
        break;
      case BEFORE_START:
        unfinishedItems = allItems[0].missions;
        break;
      case AFTER_END:
        finishedItems = allItems[0].missions;
        break;
      case BETW_THE_MISSION:
        finishedItems = allItems[0].missions.slice(0, index + 1);
        unfinishedItems = allItems[0].missions.slice(
          index + 1,
          allItems[0].missions.length
        );
        break;
      default:
        console.log("出错了");
    }
    return {
      finishedItems,
      unfinishedItems,
      state
    };

  };

  render() {
    const allItems = this.props.checkPlan.checkTodayPlan;
    const hasData = allItems && allItems[0] !== null&&allItems[0].missions.length!==0;
    
    const { finishedItems, unfinishedItems, state } = hasData?this.getTimeLineItems(allItems):{finishedItems:[],unfinishedItems:[],state:BETW_THE_MISSION};
    return (
      <View className='time-line-container'>
        {hasData ? (
          <View>
            <AtTimeline
              className={`finished-mission ${state===IN_ONE_MISSION?'current-mission':''}`}
              pending
              items={finishedItems.map((v,i,arr) => {
                return {
                  title: v.missionName,
                  content: [
                    `${v.startTime} ~ ${v.endTime}`,
                    ...v.missionDetails.split("\n")
                  ],
                  icon: state === IN_ONE_MISSION&&arr.length===i+1 ? "loading-3" 
                    :v.finished
                    ? "check-circle"
                    :"clock"
                };
              })}
            />
            <AtTimeline
              className='unfinished-mission'
              items={unfinishedItems.map(v => {
                return {
                  title: v.missionName,
                  content: [
                    `${v.startTime} ~ ${v.endTime}`,
                    ...v.missionDetails.split("\n")
                  ],
                  icon: v.finished
                  ? "check-circle"
                  :"clock"
                };
              })}
            />
          </View>
        ) : (
          <View>暂无计划，快去制定计划吧！</View>
        )}
      </View>
    );
  }
}

export default TimeLine;
